{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://mp.weixin.qq.com/s?__biz=MzkxODE3NjExOQ==&mid=2247485454&idx=1&sn=8238fec3dcf546576465f4447e8345a7&chksm=c1b42016f6c3a900497313df15caabd038f2fe2745a8f347b372a683bc82845ef333b9755139&scene=178&cur_album_id=3354758663365918722#rd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "凯利公式（Kelly Criterion）由美国科学家约翰·拉里·凯利（John Larry Kelly Jr.）在1956年提出，最初是为了解决在有噪声的信道中最大化信息传输速率的问题。但不久之后，凯利的理论被发现在赌博和投资领域具有极大的应用价值。  \n",
    "美国数学家爱德华·索普（Edward O. Thorp）是凯利公式的早期采用者，他利用该公式结合自己在21点游戏中的牌计算技巧来增加投注效率和最大化长期收益，收益颇丰。索普还专门写了一本书《击败庄家：21点的有利策略》，介绍如何应用凯利公式在赌场赚钱。后来，投资界对凯利公式进行了验证，发现公式同样适用于投资的资金管理。  \n",
    "凯利公式的核心思想是：在知道胜率（赢的概率）和赔率（每次赢得的回报）的情况下，可以计算出一个投注比例，这个比例即最大化了预期的对数财富（logarithm of wealth）的期望值，换句话说，就是最大化资本的预期几何增长率。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "f = (赔率 * 获胜概率 - 失败概率) / 赔率  \n",
    "其中：  \n",
    "f ：应该投入的资金比例  \n",
    "赔率：即盈亏比  \n",
    "获胜概率：即胜率，预测的赢得投注的概率  \n",
    "失败概率：1 - 获胜概率  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入需要使用的库\n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "# 关闭警告信息\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 获取沪深300指数10年的收盘价数据\n",
    "start_date = '20140101'  # 开始日期\n",
    "end_date = '20240911'  # 结束日期\n",
    "bars = ak.stock_zh_index_hist_csindex(symbol='000300', start_date=start_date, end_date=end_date)\n",
    "prices = bars[['日期','收盘']]\n",
    "# 将日期设置为datetime格式\n",
    "prices['日期'] = pd.to_datetime(prices['日期'])\n",
    "prices = prices.set_index('日期')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算日收益率\n",
    "returns = prices['收盘'].pct_change()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.022332384742770963\n"
     ]
    }
   ],
   "source": [
    "# 赔率 = 平均每次盈利 / 平均每次亏损\n",
    "avg_win = returns[returns > 0].mean()  # 平均每次盈利\n",
    "avg_loss = returns[returns < 0].mean()  # 平均每次亏损\n",
    "odds = abs(avg_win / avg_loss)\n",
    "\n",
    "# 胜率 = 盈利交易次数 / 总交易次数\n",
    "win_rate = (returns > 0).sum() / returns.count()\n",
    "# 失败率 = 1- 胜率\n",
    "lose_rate = 1 - win_rate\n",
    "\n",
    "# f = (赔率 * 胜率 - 失败率) / 赔率\n",
    "f =  ((odds * win_rate) - lose_rate) / odds\n",
    "print(f)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "4broker",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
